﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Parallaxing : MonoBehaviour {

    public Transform[] backgrounds;
    public float[] parallaxScales;
    public float smoothing;

    public Transform cam;
    private Vector3 previousCamPos;
    public bool isFollow = false;
    void OnEnable()
    {
        GameManager.GameStateChanged += OnGameStateChanged;
  
    }

    void OnDisable()
    {
        GameManager.GameStateChanged -= OnGameStateChanged;
       
    }

    void OnGameStateChanged(GameState newState, GameState oldState)
    {
        if (newState == GameState.Playing)
        {
            isFollow = true;
            cam = Camera.main.transform;
            previousCamPos = cam.position;
            parallaxScales = new float[backgrounds.Length];
            for (int i = 0; i < backgrounds.Length; i++)
            {
                parallaxScales[i] = backgrounds[i].position.z * -1;
            }

        }

    }
    private void Awake()
    {
       
    }
    // Use this for initialization
    void Start () {
         

    }
	
	// Update is called once per frame
	void Update () {
        if (isFollow)
        {
            for (int i = 0; i < backgrounds.Length; i++)
            {
                float parallax = (previousCamPos.x - cam.position.x) * parallaxScales[i];

                float backGrTargetPosX = backgrounds[i].position.x + parallax;
                Vector3 backGrTargetPos = new Vector3(backGrTargetPosX, backgrounds[i].position.y, backgrounds[i].position.z);

                backgrounds[i].position = Vector3.Lerp(backgrounds[i].position, backGrTargetPos, smoothing * Time.deltaTime);
            }

            previousCamPos = cam.position;
        }
    }
}
